package com.atstudying.mall.product.service.impl;

import com.atstudying.common.constant.ProductConstant;
import com.atstudying.common.utils.PageUtils;
import com.atstudying.common.utils.Query;
import com.atstudying.mall.product.dao.AttrAttrgroupRelationDao;
import com.atstudying.mall.product.dao.AttrDao;
import com.atstudying.mall.product.dao.AttrGroupDao;
import com.atstudying.mall.product.dao.CategoryDao;
import com.atstudying.mall.product.entity.*;
import com.atstudying.mall.product.service.AttrService;
import com.atstudying.mall.product.service.CategoryService;
import com.atstudying.mall.product.vo.AttrRespVo;
import com.atstudying.mall.product.vo.AttrVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Autowired
    AttrAttrgroupRelationDao relationDao;

    @Autowired
    AttrDao attrDao;

    @Autowired
    CategoryService categoryService;
    @Autowired
    AttrGroupDao attrGroupDao;

    @Autowired
    CategoryDao categoryDao;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        //分页方法
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void saveAttr(AttrVo attr) {

        AttrEntity attrEntity=new AttrEntity();

        //1：保存基本数据
        //将页面attr来的值最后封装到attrEntity中
        BeanUtils.copyProperties(attr,attrEntity);
        this.save(attrEntity);
        //2：保存关联关系

        //只有是基本属性才要保存分组关系，销售属性不用保存分组关系
        if (attr.getAttrType()== ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode() && attr.getAttrGroupId()!=null){
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity=new AttrAttrgroupRelationEntity();
            attrAttrgroupRelationEntity.setAttrGroupId(attr.getAttrGroupId());
            attrAttrgroupRelationEntity.setAttrId(attrEntity.getAttrId());
            relationDao.insert(attrAttrgroupRelationEntity);

        }


//        log.info(String.valueOf(attrEntity));
//        log.info(String.valueOf(attrAttrgroupRelationEntity));



    }

    @Override
    public PageUtils queryBaseAttrPage(Map<String, Object> params, Long catelogId, String type) {
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<AttrEntity>().eq("attr_type","base".equalsIgnoreCase(type)?ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode():ProductConstant.AttrEnum.ATTR_TYPE_SALE.getCode());

        if (catelogId!=0){
            //基本属性等于1否则就是0（类型是基本类型就查1，否则就查0
            queryWrapper.eq("catelog_id",catelogId);

        }
        String key= (String) params.get("key");
        if (!StringUtils.isEmpty(key)){
            //attr_id attr_name
            queryWrapper.and((wrapper)->{
                wrapper.eq("attr_Id",key).or().like("attr_name",key);
            });
        }
        //我们调用this.page方法先将分页条件封装成IPage参数
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                queryWrapper
        );

        PageUtils pageUtils = new PageUtils(page);

        //从真正获取到的page里面获取到查询记录
        List<AttrEntity> records = page.getRecords();

        //使用流失编程
        List<AttrRespVo> attrRespVos = records.stream().map((attrEntity) -> {
            AttrRespVo attrRespVo = new AttrRespVo();

            BeanUtils.copyProperties(attrEntity, attrRespVo);
            //1：设置三级分类名和分组的名字，然后返回给前端

            if ("base".equalsIgnoreCase(type)) {
                AttrAttrgroupRelationEntity attrId = relationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrEntity.getAttrId()));
                if (attrId != null && attrId.getAttrGroupId()!=null) {
                    AttrGroupEntity attr_group_id = attrGroupDao.selectOne(new QueryWrapper<AttrGroupEntity>().eq("attr_group_id", attrId.getAttrGroupId()));
                    attrRespVo.setGroupName(attr_group_id.getAttrGroupName());

                }
            }

            CategoryEntity categoryEntity = categoryDao.selectById(attrEntity.getCatelogId());
            if (categoryEntity != null) {
                attrRespVo.setCatelogName(categoryEntity.getName());

            }
            return attrRespVo;
        }).collect(Collectors.toList());

        pageUtils.setList(attrRespVos);
        return pageUtils;

    }

    @Override
    public AttrRespVo getAttrInfo(Long attrId) {

        AttrRespVo respVo=new AttrRespVo();
        AttrEntity attrEntity = this.getById(attrId);

        BeanUtils.copyProperties(attrEntity,respVo);


        if (attrEntity.getAttrType()==ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()){
            //1，设置分组信息
            AttrAttrgroupRelationEntity attrgroupRelation= relationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrId));

            log.info(String.valueOf("attrgroupRelation："+attrgroupRelation));
            if (attrgroupRelation!=null) {
                respVo.setAttrGroupId(attrgroupRelation.getAttrGroupId());
                log.info(String.valueOf("AttrGroupId："+attrgroupRelation.getAttrGroupId()));

                //这里出现错误
                AttrGroupEntity attrGroupEntity = attrGroupDao.selectById( attrgroupRelation.getAttrGroupId());
                log.info(String.valueOf("attrGroupEntity："+attrGroupEntity));

                if (attrGroupEntity != null) {
                    respVo.setGroupName(attrGroupEntity.getAttrGroupName());
                }
            }
        }




        //2：设置三级分类信息
        Long catelogId=attrEntity.getCatelogId();
        Long[] catelogPath=categoryService.findCatelogPath(catelogId);
        respVo.setCatelogPath(catelogPath);

        CategoryEntity categoryEntity=categoryDao.selectById(catelogId);
        respVo.setCatelogName(categoryEntity.getName());
        return respVo;
    }

    @Transactional
    @Override
    public void updateAttr(AttrVo attr) {

        AttrEntity attrEntity=new AttrEntity();
        BeanUtils.copyProperties(attr,attrEntity);
        this.updateById(attrEntity);
        //1：修改分组关联
        AttrAttrgroupRelationEntity relationEntity=new AttrAttrgroupRelationEntity();
        if (attrEntity.getAttrType()==ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()){


            relationEntity.setAttrGroupId(attr.getAttrGroupId());
            relationEntity.setAttrId(attr.getAttrId());

        }

        //根据一个条件统计数量
        Integer integer = relationDao.selectCount(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId()));
        System.out.println("根据一个条件统计数量："+integer);
        if (integer>0){

            relationDao.update(relationEntity,new UpdateWrapper<AttrAttrgroupRelationEntity>().eq("attr_id",attr.getAttrId()));
        }else {

            relationDao.insert(relationEntity);
        }
    }

    /**
     * 根据分组id查找关联的所有基本属性
     * @param attrgroupId
     * @return
     */
    @Override
    public List<AttrEntity> getRelationAttr(Long attrgroupId) {

        List<AttrAttrgroupRelationEntity> entities = relationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", attrgroupId));

        List<Long> attrIds = entities.stream().map((attr) -> {
            return attr.getAttrId();
        }).collect(Collectors.toList());

        //非空判断：才可以去数据库里修改
        if (attrIds==null || attrIds.size()==0){
            return null;
        }
        //查询到所有关联表中的属性id，调用如下方法查出所有属性表中的值
        Collection<AttrEntity> attrEntities = this.listByIds(attrIds);
        return (List<AttrEntity>) attrEntities;
    }

    ///product/attrgroup/{attrgroupId}/noattr/relation

    @Override
    public void deleteRelation(AttrAttrgroupRelationEntity[] vos) {

        //我们要实现只发一次请求，完成批量删除
       // relationDao.delete(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id",1L).eq("attr_group_id",1l));

        //把两个数组，变成AttrAttrgroupRelationEntity的集合
        List<AttrAttrgroupRelationEntity> entities = Arrays.asList(vos).stream().map((item) -> {
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            BeanUtils.copyProperties(item, relationEntity);
            return relationEntity;
        }).collect(Collectors.toList());

        relationDao.deleteBatchRelation(entities);
    }

    /***
     * 获取当前分组没有关联的属性
     * @param attrgroupId
     * @param param
     * @return
     */
    @Override
    public PageUtils getNoRelationAttr(Long attrgroupId, Map<String, Object> param) {

        //1：当前分组只可以关联自己所属的三级分类里面的所有属性

        AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrgroupId);

        //以后只可以查该三级分类下的id
        Long catelogId = attrGroupEntity.getCatelogId();

        //2：当前分组只可以关联别的分组没有引用的属性

        //2.1）当前分类下的其他分组
        List<AttrGroupEntity> group = attrGroupDao.selectList(new QueryWrapper<AttrGroupEntity>().eq("catelog_id", catelogId));

        List<Long> collect = group.stream().map((item) -> {
            return item.getAttrGroupId();
        }).collect(Collectors.toList());

        //2.2 这些分组关联的属性
        List<AttrAttrgroupRelationEntity> groupId = relationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().in("attr_group_id", collect));

        List<Long> attrIds = groupId.stream().map((Item) -> {
            return Item.getAttrId();
        }).collect(Collectors.toList());

        //2.3 从当前分类的所有属性中移除这些属性
//        List<AttrEntity> attrEntities = this.baseMapper.selectList(new QueryWrapper<AttrEntity>().eq("catelog_Id", catelogId).notIn("attr_id", attrIds));
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<AttrEntity>().eq("catelog_Id", catelogId).eq("attr_type",ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode());

        if (attrIds!=null && attrIds.size()>0){
            wrapper.notIn("attr_id", attrIds);
        }
        String key = (String) param.get("key");

        if (!StringUtils.isEmpty(key)){
            wrapper.and((w)->{
                w.eq("attr_id",key).or().like("attr_name",key);
            });
        }
        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(param), wrapper);
        PageUtils pageUtils = new PageUtils(page);
        return  pageUtils;
    }
    /**
     * 在指定的所有数据集合里面，挑选出检索属性
     * @param attrIds
     * @return
     */
    @Override
    public List<Long> selectSearchAttrs(List<Long> attrIds) {

//        List<Long> longs = baseMapper.selectSearchAttrIds(attrIds);

        return baseMapper.selectSearchAttrIds(attrIds);
    }

}